/*
 * Copyright 2017 Baiyyy
 * @(#)ColdStorageService.java
 */

package com.byyy.ccts.modules.ysjl.service.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.byyy.ccts.core.common.service.impl.CommonServiceImpl;
import com.byyy.ccts.core.query.data.Page;
import com.byyy.ccts.core.query.data.PageImpl;
import com.byyy.ccts.core.query.data.Pageable;
import com.byyy.ccts.core.query.data.Queryable;
import com.byyy.ccts.core.query.parse.QueryToWrapper;
import com.byyy.ccts.core.query.wrapper.EntityWrapper;
import com.byyy.ccts.core.utils.StringUtils;
import com.byyy.ccts.core.utils.http.HttpUtils;
import com.byyy.ccts.core.utils.upload.FileUploadUtils;
import com.byyy.ccts.modules.ysjl.YsjlGlobal;
import com.byyy.ccts.modules.ysjl.entity.YsjlUser;
import com.byyy.ccts.modules.ysjl.entity.YsjlUserAbility;
import com.byyy.ccts.modules.ysjl.mapper.YsjlUserMapper;
import com.byyy.ccts.modules.ysjl.service.IYsjlUserAbilityService;
import com.byyy.ccts.modules.ysjl.service.IYsjlUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by DELL on 2018-6-13.
 */
@Transactional
@Service("ysjlUserService")
public class YsjlUserService extends CommonServiceImpl<YsjlUserMapper, YsjlUser> implements IYsjlUserService {

    @Autowired
    private IYsjlUserAbilityService ysjlUserAbilityService;

    @Override
    public Page<YsjlUser> pageUserList(Queryable queryable, EntityWrapper<YsjlUser> wrapper) {
        QueryToWrapper<YsjlUser> queryToWrapper = new QueryToWrapper<>();
        // 排序问题
        queryToWrapper.parseCondition(wrapper, queryable);
        queryToWrapper.parseSort(wrapper, queryable);
        Pageable pageable = queryable.getPageable();
        com.baomidou.mybatisplus.plugins.Page<YsjlUser> page = new com.baomidou.mybatisplus.plugins.Page<YsjlUser>(
                pageable.getPageNumber(), pageable.getPageSize());
        com.baomidou.mybatisplus.plugins.Page<YsjlUser> content = this.listPage(page, wrapper);
        List<YsjlUser> userList = content.getRecords();
        if (userList != null && !userList.isEmpty()) {
            for (YsjlUser user : userList) {
                user.setName(YsjlGlobal.decodeName(user.getName()));
                user.setNickName(YsjlGlobal.decodeName(user.getNickName()));
            }
        }

        return new PageImpl<YsjlUser>(userList, queryable.getPageable(), content.getTotal());
    }

    public com.baomidou.mybatisplus.plugins.Page<YsjlUser> listPage(com.baomidou.mybatisplus.plugins.Page<YsjlUser> page, Wrapper<YsjlUser> wrapper) {
        page.setRecords(baseMapper.queryUserListPage(page, wrapper));
        return page;
    }

    @Override
    public YsjlUser wxAuth(String code) {
        String res = HttpUtils.get("https://api.weixin.qq.com/sns/jscode2session", "appid=wxe45a395077d171ea&secret=21af424dfe7d7fa9a58d1dd7bb611cf6&js_code="
                + code + "&grant_type=authorization_code");

        ObjectMapper mapper = new ObjectMapper();
        Map<String, String> map = null;
        try {
            map = mapper.readValue(res, Map.class);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        YsjlUser ysjlUser = null;
        String openid = map.get("openid");
        if (StringUtils.isNotEmpty(openid)) {
            ysjlUser = this.baseMapper.queryUserByOpenid(openid);
        }

        if (ysjlUser == null) {
            ysjlUser = new YsjlUser();
            ysjlUser.setOpenid(openid);
        }
        else {
            ysjlUser.setLoginCnt(ysjlUser.getLoginCnt() + 1);
            ysjlUser.setLoginTime(new Timestamp(System.currentTimeMillis()));
            this.updateById(ysjlUser);
            List<YsjlUserAbility> abilityList = this.ysjlUserAbilityService.queryByUserId(ysjlUser.getId());
            List<Integer> scoreList = new ArrayList<>();
            for (YsjlUserAbility ability : abilityList) {
                scoreList.add(ability.getScore());
            }
            ysjlUser.setAbilityList(scoreList);
        }

        ysjlUser.setName(YsjlGlobal.decodeName(ysjlUser.getName()));
        ysjlUser.setNickName(YsjlGlobal.decodeName(ysjlUser.getNickName()));
        return ysjlUser;
    }

    @Override
    public String uploadPic(HttpServletRequest request, MultipartFile file) {
        String url = null;
        StringBuffer requestURL = request.getRequestURL();
        String path = requestURL.toString().substring(0, requestURL.toString().indexOf(request.getServletPath()));
        try {
            url = FileUploadUtils.upload(request, "static/ysjl", file, new String[]{"gif", "jpg", "jpeg", "png", "bmp"}, 104857600,
                    true);
            url = path + "/" + url;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return url;
    }

    @Override
    public YsjlUser register(YsjlUser ysjlUser) {
        YsjlUser user = this.baseMapper.queryUserByOpenid(ysjlUser.getOpenid());
        String userName = ysjlUser.getName();
        if (userName.length() > 15) {
            userName = userName.substring(0, 15);
        }
        String encodeName = YsjlGlobal.encodeName(userName);
        if (user != null) {
            user.setName(encodeName);
            if (StringUtils.isNotEmpty(ysjlUser.getPic())) {
                user.setPic(ysjlUser.getPic());
            }
            user.setEditTime(new Timestamp(System.currentTimeMillis()));
            this.updateById(user);
            List<YsjlUserAbility> abilityList = this.ysjlUserAbilityService.queryByUserId(user.getId());
            List<Integer> scoreList = new ArrayList<>();
            for (YsjlUserAbility ability : abilityList) {
                scoreList.add(ability.getScore());
            }
            user.setAbilityList(scoreList);
            user.setName(YsjlGlobal.decodeName(user.getName()));
            if (StringUtils.isEmpty(ysjlUser.getRacket())) {
                ysjlUser.setRacket("小黑拍！");
            }
            user.setRacket(YsjlGlobal.ROCKET_LEVEL[user.getRank() - 1] + ysjlUser.getRacket());
            return user;
        }
        else {
            if (StringUtils.isEmpty(ysjlUser.getPic())) {
                ysjlUser.setPic("http://ccc.baheal.com/byyyccctest/static/ysjl/logo/logoVertical.png");
            }
            else {
                ysjlUser.setPic(ysjlUser.getPic());
            }
            ysjlUser.setLoginCnt(1);
            ysjlUser.setRank(1);
            ysjlUser.setName(encodeName);
            ysjlUser.setNickName(encodeName);
            if (StringUtils.isEmpty(ysjlUser.getRacket())) {
                ysjlUser.setRacket("小黑拍！");
            }
            ysjlUser.setRacket(YsjlGlobal.ROCKET_LEVEL[0] + ysjlUser.getRacket());
            ysjlUser.setAddTime(new Timestamp(System.currentTimeMillis()));
            ysjlUser.setEditTime(new Timestamp(System.currentTimeMillis()));
            ysjlUser.setLoginTime(new Timestamp(System.currentTimeMillis()));
            this.insert(ysjlUser);
            List<YsjlUserAbility> abilityList = new ArrayList<>(6);
            YsjlUserAbility userAbility = null;
            for (int i = 0; i < 6; i++) {
                userAbility = new YsjlUserAbility();
                userAbility.setUserId(ysjlUser.getId());
                userAbility.setAbilityId(i + 1);
                userAbility.setScore(50);
                abilityList.add(userAbility);
            }
            ysjlUserAbilityService.insertBatch(abilityList);
            ysjlUser.setAbilityList(Arrays.asList(new Integer[]{0, 0, 0, 0, 0, 0}));
        }
        ysjlUser.setName(userName);
        ysjlUser.setNickName(userName);
        return ysjlUser;
    }

    @Override
    public YsjlUser queryByName(String name) {
        return this.baseMapper.queryByName(name);
    }

    @Override
    public YsjlUser userInfo(String id) {
        YsjlUser ysjlUser = this.selectById(id);
        ysjlUser.setName(YsjlGlobal.decodeName(ysjlUser.getName()));
        ysjlUser.setNickName(YsjlGlobal.decodeName(ysjlUser.getNickName()));
        List<YsjlUserAbility> abilityList = this.ysjlUserAbilityService.queryByUserId(ysjlUser.getId());
        ysjlUser.setUserAbilityList(abilityList);
        return ysjlUser;
    }

    @Override
    public String submit(YsjlUser ysjlUser) {
        YsjlUser user = selectById(ysjlUser.getId());
        if (user.getRank() != ysjlUser.getRank()) {
            if (ysjlUser.getRank() - user.getRank() != 1)
                return "只能提升一等级";
            if (user.getScore() < YsjlGlobal.RANK_SCORE_MAP.get(user.getRank()))
                return "积分不够提升";
            user.setCurrentScore(user.getScore() - YsjlGlobal.RANK_SCORE_MAP.get(user.getRank()));
        }
        user.setVipLevel(ysjlUser.getVipLevel());
        if (user.getVipStyle() > 0) {
            Calendar calendar = Calendar.getInstance();
            Date now = new Date();
            calendar.setTime(now);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.add(Calendar.MONTH, 1);
            user.setVipEndDate(new Timestamp(calendar.getTimeInMillis()));
        }
        user.setRank(ysjlUser.getRank());
        user.setVipStyle(ysjlUser.getVipStyle());
        user.setNickName(ysjlUser.getNickName());
        updateById(user);
        this.ysjlUserAbilityService.updateBatchById(ysjlUser.getUserAbilityList());
        return null;
    }

    @Override
    public List<YsjlUser> queryVipOverUser() {
        return this.baseMapper.queryVipOverUser();
    }
}
